var minesMap = [];
	var mines = [];
	var flags = 0;
	var seconds  = 60;
	var label = null;
	var t1 = null;
//	window.onload = function(){
		//create layout coorinate
	
//	}
var layout = {
		row : 0,
		col : 0 ,		
		mine : 0
	};

function minesCoordiate() {
		for(var i=0; i<layout.row ; i++){
			var item = [];
			for (var j = 0 ; j < layout.col; j++) {
				item.push({
					value : null,
					isTread : false,
					isMarked : false,
					isCleared : false
				});
			}
			minesMap.push(item);
		}
	}
	// create mines coordinate
	function createMines(){
		var i = 0 ;
		while (i < layout.mine){
			var mine = {
				row : randomCoordinate(layout.row,0),
				col : randomCoordinate(0,layout.col)
				// row : 8,
				// col : 8
			}
			if(checkDuplicated(mine)){
				continue ;
			}else{
				//console.
				minesMap[mine.row][mine.col].value = 'Mine';
				minesMap[mine.row][mine.col].isTread = true;
				mines.push(mine);
				i++;
			}
		}
	}

	function createMineLayout(){
		for(var i = 0 ; i < layout.row ; i++){
			 oul = document.createElement('ul');
			document.getElementById('minesLayout').appendChild(oul);
			for(var j = 0; j < layout.col ;j++){
				oli = document.createElement('li');
				oli.x = i;
				oli.y = j;
				minesMap[i][j].oli = oli;
				//oli.innerHTML = minesMap[i][j].value;
				oul.appendChild(oli);
			}
		}
		
	}
	
	//get a coordinate by a random algorithm
	function randomCoordinate(row,col){
		if(row != 0){
			return parseInt(Math.random()*row);
		}else{
			return parseInt(Math.random()*col);
		}
	}

	//check if the coordinate for this mine is existed 
	function checkDuplicated(mine){
		for(var i = 0 ;i<mines.length; i++){
			if(mines[i].row == mine.row && mines[i].col == mine.col){
				return true;
			}
		}
		return false;
	}

	//calculate the mines number
	function calculateMinesSigns() {
		var count = null;
		for(var i=0; i<layout.row;i++ ){
			for(var j= 0; j<layout.col ;j++){
				var item = minesMap[i][j];
				count = 0;
				if(item.value != 'Mine'){
				getRound(i, j).forEach(function(value){
					if(minesMap[value.row][value.col].value == 'Mine'){
						count++;
					}
				});
				item.value = count;	
				}
			}
		}
	}

	//get rounding 8 coordinates for one minesMap(i,j)
	function getRound(i,j,tag){
		var item = [];
		for(var x = i-1 ;x <=i+1 ; x++){
			for(var y = j-1 ; y<= j+1 ; y++){
				if(x == i && y == j){ continue;}
				if(x >= 0 && x <layout.row && y>=0 && y <layout.col){
					item.push({row :x ,col :y});
				}
			}
		}	
		return item;
	}

	function getGrid(i,j){
		var item = [];
		for(var x = i-1 ;x <=i+1 ; x++){
			for(var y = j-1 ; y<= j+1 ; y++){
				if(x == i && y == j){ continue;}				
				if(x >= 0 && x <layout.row && y>=0 && y <layout.col ){
					var point = minesMap[x][y];
					if(!point.isCleared && !point.isTread && !point.isMarked){
					item.push({row :x ,col :y});
				}
				}
			}
		}	
		return item;
	}
	function createMouseEvent(){
		//close mouse menu
		document.body.oncontextmenu= function(e){
			e.preventDefault();
			return false;
		}
		var olis = [];
		olis = document.querySelectorAll('li');
		olis.forEach(function(value){		
			value.onmousedown = function(event){				
				event = event||window.event;
				if(event.which == 1){
					var point = {};
					point.row = this.x ;
					point.col = this.y ;
					if(point.isTread){
						lose();
					}//it is cleared or number;
					else if(point.isCleared){
						return;
					}						
					// it is unknown area
					else {
						if(minesMap[point.row][point.col].isTread){
							lose();
						}
						var staged= [];
						var unStaged = [];
						var temp = null ;
						unStaged.push(point);
						while(unStaged.length>0&&unStaged.length <100){
							 	var value = unStaged[0];
							 	//console.log(value.row +","+value.col);						
								temp = minesMap[value.row][value.col];
								temp.isCleared = true;
									staged.push(value);
									console.log(staged.length);
													
								if(temp.value == 0){									
									unStaged.add(unStaged,getGrid(value.row,value.col),staged);
								}
								// console.log("unStaged size " + unStaged.length);
								// console.log("staged size "+ staged.length);
								unStaged.splice(0,1);
							 						
						}
						//show html according the staged array
						createHTML(staged);
					}
				}else{
					var point = minesMap[this.x][this.y];
					if(point.isCleared){
						return;
					}else if(point.isMarked){
						point.oli.className = '';
						point.isMarked = false;
					}
					else{
						point.isMarked = true;
						point.oli.className= 'marked';
						if(point.isTread){
							flags ++;
						}
						if(flags == mines.length){
							win();
						}
					}
				}

			}
		});		
	}
	//when you lose
	function lose(){
		var p = null;
		for(var i = 0; i< mines.length;i++){
			p = document.createElement('div');
			p.className='bomb';
			minesMap[mines[i].row][mines[i].col].oli.appendChild(p);
		}
		clearTimeout(t1);
		alert("you lose");
	}
	function win(){
		clearTimeout(t1);
		alert("you win ");
	}
	Array.prototype.remove = function(val){
		var index = this.findValue(val);
		if(index > -1 ){
			this.splice(index,1);
		}
	}

	Array.prototype.add = function(destination,source,staged){
		source.forEach(function(value,index){
			staged.forEach(function(item){
				if(value.row == item.row && value.col == item.col){
					source.splice(index,1);
				}
			});
		});
		var point = null;
		for(i =0 ;i< source.length; i++){
			point = source[i];
			var flag = false;
			for(var j = 0 ; j < destination.length ; j ++){
				if(destination[j].row == point.row && destination[j].col ==  point.col){
					flag = true;
				}
		
			}
			if(!flag){
				destination.push(point);
			}	
		}
		//destination.push.apply(destination,source);
		//console.log("unStaged length is "+destination.length);
	}

	Array.prototype.findValue = function(value){
		//console.log(this);
		return this.findIndex(function(element){
			return element.row == value.row && element.col == value.col;
		});

	}
	function createHTML(array){
		//console.log(array.length);
		var item;
		for(var i = 0 ; i < array.length ; i++){ 
			item = minesMap[array[i].row][array[i].col];					
			if( item.value == 0){					
					item.oli.className = 'clear';

			}else if(item.value>0){
					item.oli.innerHTML = item.value;			
					item.oli.className = 'level';
			}	
		}
	}

	// init the mine map
	function init(){
		minesCoordiate();
		createMines();
		calculateMinesSigns();
		createMineLayout();	
		createMouseEvent();	 
	}
	//var t = null;
	//t = setTimeout(time,1000);
	// function time(){
	// 	clearTimeout(t);
	// 	dt = new Date();
	// 	var h = dt.getHours();
	// 	var m = dt.getMinutes();
	// 	var s = dt.getSeconds();
	// 	document.getElementById('timeshow').innerHTML = h +"hours" + m +"minutes"+s;
	// 	t = setTimeout(time,1000);
	// }
	
	//count down clock
	function countDown(){
		var row = 0;
		var col = 0;
		var mines = 0;
		document.getElementById('btn1').disabled = true;

		var option = document.getElementById('sec').value;

		switch(parseInt(option)){
			case 10 : row = 10; col =10 ; mines =10; break;
			case 20 : row = 9; col =18 ; mines =30; break;
			case 30 : row = 10; col =20 ; mines =40; break;
		}
		layout = {
			row:row,
			col:col,
			mine:mines
		}

		init();

		label = document.getElementById('timeshow');

		label.innerHTML = '倒计时 ：  00 : '+seconds;
		
		t1 = setTimeout('reduceTime()',1000);


	}
	//count time
	function reduceTime(){
		clearTimeout(t1);
		var time = seconds -- ;
		
		label.innerHTML = '倒计时 ：  00 : '+(time<10?'0'+time :time);
		console.log(seconds);
		if(seconds >0 ){
		t1 = setTimeout('reduceTime()',1000);
		}else{
		 lose();
		}

	}

	function restart(){
		document.getElementById('minesLayout').innerHTML= '';
		clear();
		clearTimeout(t1);
		seconds = 60;
		countDown();
	}

	function clear(){
		minesMap = [];
		mines = [];
		flags = 0;
		seconds  = 60;
		label = null;
		t1 = null;
	}

	//select change
	function changeValue(){
		document.getElementById('btn1').disabled = false;
	}
